<template>
  <div class="progress-page">
    <header class="header">
      <div class="header-left">
        <el-button type="text" @click="$router.back()"><el-icon><ArrowLeft /></el-icon></el-button>
        <h1>诊断进度查询</h1>
      </div>
    </header>
    
    <div class="content">
      <el-card class="progress-card">
        <template #header>
          <div class="card-header">
            <span>我的诊断进度列表</span>
          </div>
        </template>
        
        <el-table :data="diagnosisList" style="width: 100%">
          <el-table-column prop="id" label="申请ID" width="100"></el-table-column>
          <el-table-column prop="imageType" label="影像类型" width="120"></el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.uploadTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="当前状态" width="150">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="完成进度" width="180">
            <template #default="scope">
              <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)" :color="getStatusColor(scope.row.status)"></el-progress>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewProgressDetail(scope.row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 进度详情对话框 -->
      <el-dialog
        v-model="detailVisible"
        title="诊断进度详情"
        width="700px"
        :before-close="handleClose"
      >
        <div v-if="selectedDiagnosis" class="progress-detail">
          <div class="detail-header">
            <h3>申请信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">申请ID：</span>
                <span class="value">{{ selectedDiagnosis.id }}</span>
              </div>
              <div class="info-item">
                <span class="label">影像类型：</span>
                <span class="value">{{ selectedDiagnosis.imageType }}</span>
              </div>
              <div class="info-item">
                <span class="label">上传时间：</span>
                <span class="value">{{ formatDate(selectedDiagnosis.uploadTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">当前状态：</span>
                <el-tag :type="getStatusType(selectedDiagnosis.status)">
                  {{ getStatusText(selectedDiagnosis.status) }}
                </el-tag>
              </div>
            </div>
          </div>
          
          <div class="process-timeline">
            <h3>处理流程</h3>
            <el-timeline>
              <el-timeline-item
                v-for="(step, index) in processSteps"
                :key="index"
                :timestamp="step.timestamp ? formatDate(step.timestamp) : ''"
                :type="step.status"
                :icon="step.icon"
                :hollow="!step.completed"
              >
                <div class="timeline-content">
                  <h4>{{ step.title }}</h4>
                  <p v-if="step.description">{{ step.description }}</p>
                  <span v-if="!step.completed" class="pending-text">等待处理...</span>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
          
          <div class="download-section" v-if="selectedDiagnosis">
            <h3>相关资料</h3>
            <div class="image-preview" v-if="selectedDiagnosis?.imageUrl">
              <h4>影像预览</h4>
              <img :src="selectedDiagnosis.imageUrl" alt="医学影像" class="medical-image">
            </div>
            <el-button type="success" icon="Download" @click="downloadImage">下载影像</el-button>
            <el-button type="primary" icon="DocumentCopy" @click="shareReport" v-if="selectedDiagnosis.status === 'completed'">分享报告</el-button>
          </div>
        </div>
        
        <template #footer>
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="goToReport" v-if="selectedDiagnosis?.reportGenerated && selectedDiagnosis?.finalReport">查看完整报告</el-button>
        </template>
      </el-dialog>
      
      <!-- 分享对话框 -->
      <el-dialog
        v-model="shareVisible"
        title="分享报告"
        width="500px"
        :before-close="closeShareDialog"
      >
        <div class="share-dialog">
          <el-form label-position="top">
            <el-form-item label="分享链接（有效期24小时）">
              <el-input v-model="shareLink" readonly></el-input>
              <el-button type="primary" @click="copyLink">复制链接</el-button>
            </el-form-item>
            <el-form-item label="二维码">
              <div class="qrcode-container">
                <div class="qrcode-placeholder">二维码图片</div>
                <p class="qrcode-hint">扫码查看诊断报告</p>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button @click="closeShareDialog">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { ArrowLeft, Download, DocumentCopy } from '@element-plus/icons-vue';

export default {
  name: 'DiagnosisProgress',
  components: {
    ArrowLeft,
    Download,
    DocumentCopy
  },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const diagnosisList = ref([]);
    const detailVisible = ref(false);
    const selectedDiagnosis = ref(null);
    const shareVisible = ref(false);
    const shareLink = ref('');
    
    // 模拟诊断进度数据
    const mockDiagnosisData = [
      {
        id: 'D-20241031-001',
        imageType: '胸部X光片',
        uploadTime: '2024-10-31T08:30:00Z',
        status: 'completed',
        progress: 100,
        imageUrl: 'http://localhost:3001/uploads/image-1728345678901.jpg',
        processSteps: [
          {
            title: '图像采集',
            description: '已完成胸部X光片拍摄',
            timestamp: '2024-10-31T08:30:00Z',
            status: 'success',
            icon: 'el-icon-check',
            completed: true
          },
          {
            title: 'AI分析',
            description: 'AI模型已完成初步筛查',
            timestamp: '2024-10-31T08:45:00Z',
            status: 'success',
            icon: 'el-icon-check',
            completed: true
          },
          {
            title: '医生复核',
            description: '王医生已完成专业复核',
            timestamp: '2024-10-31T09:30:00Z',
            status: 'success',
            icon: 'el-icon-check',
            completed: true
          },
          {
            title: '报告生成',
            description: '诊断报告已生成',
            timestamp: '2024-10-31T09:35:00Z',
            status: 'success',
            icon: 'el-icon-check',
            completed: true
          }
        ]
      },
      {
        id: 'D-20241031-002',
        imageType: 'CT扫描',
        uploadTime: '2024-10-31T10:15:00Z',
        status: 'processing',
        progress: 50,
        imageUrl: 'http://localhost:3001/uploads/image-1728345678902.jpg',
        processSteps: [
          {
            title: '图像采集',
            description: '已完成CT扫描',
            timestamp: '2024-10-31T10:15:00Z',
            status: 'success',
            icon: 'el-icon-check',
            completed: true
          },
          {
            title: 'AI分析',
            description: 'AI模型正在进行分析中...',
            timestamp: '2024-10-31T10:20:00Z',
            status: 'warning',
            icon: 'el-icon-loading',
            completed: true
          },
          {
            title: '医生复核',
            description: '',
            timestamp: '',
            status: 'primary',
            icon: '',
            completed: false
          },
          {
            title: '报告生成',
            description: '',
            timestamp: '',
            status: 'primary',
            icon: '',
            completed: false
          }
        ]
      },
      {
        id: 'D-20241031-003',
        imageType: '核磁共振',
        uploadTime: '2024-10-31T14:00:00Z',
        status: 'pending',
        progress: 25,
        imageUrl: 'http://localhost:3001/uploads/image-1728345678903.jpg',
        processSteps: [
          {
            title: '图像采集',
            description: '已完成核磁共振扫描',
            timestamp: '2024-10-31T14:00:00Z',
            status: 'success',
            icon: 'el-icon-check',
            completed: true
          },
          {
            title: 'AI分析',
            description: '',
            timestamp: '',
            status: 'primary',
            icon: '',
            completed: false
          },
          {
            title: '医生复核',
            description: '',
            timestamp: '',
            status: 'primary',
            icon: '',
            completed: false
          },
          {
            title: '报告生成',
            description: '',
            timestamp: '',
            status: 'primary',
            icon: '',
            completed: false
          }
        ]
      }
    ];
    
    onMounted(() => {
      loadDiagnosisData();
    });
    
    const loadDiagnosisData = async () => {
      try {
        // 实际项目中这里应该调用API获取数据
        console.log('正在加载诊断进度数据...');
        // 获取患者的影像和报告数据
        const patientId = userStore.currentUser?.patientId;
        if (patientId) {
          // 调用后端API获取患者的影像数据
          const response = await fetch(`http://localhost:3001/api/ai-reports/patient/${patientId}`);
          const reports = await response.json();
          
          if (Array.isArray(reports) && reports.length > 0) {
            // 将API返回的数据转换为诊断进度列表格式
            diagnosisList.value = reports.map(report => ({
              id: `D-${report.id}`,
              imageType: '医学影像',
              uploadTime: report.analysisTime || new Date().toISOString(),
              status: report.reviewStatus === '已复核' ? 'completed' : 'processing',
              progress: report.reviewStatus === '已复核' ? 100 : 50,
              imageUrl: `http://localhost:3001/uploads/${report.imageFilename}`,
              processSteps: [
                {
                  title: '图像采集',
                  description: '已完成影像采集',
                  timestamp: report.analysisTime,
                  status: 'success',
                  icon: 'el-icon-check',
                  completed: true
                },
                {
                  title: 'AI分析',
                  description: report.details,
                  timestamp: report.analysisTime,
                  status: 'success',
                  icon: 'el-icon-check',
                  completed: true
                },
                {
                  title: '医生复核',
                  description: report.doctorComment || (report.reviewStatus === '已复核' ? '医生已完成复核' : '等待医生复核'),
                  timestamp: report.analysisTime,
                  status: report.reviewStatus === '已复核' ? 'success' : 'warning',
                  icon: report.reviewStatus === '已复核' ? 'el-icon-check' : 'el-icon-loading',
                  completed: report.reviewStatus === '已复核'
                },
                {
                  title: '报告生成',
                  description: report.reviewStatus === '已复核' ? '诊断报告已生成' : '',
                  timestamp: report.reviewStatus === '已复核' ? report.analysisTime : '',
                  status: report.reviewStatus === '已复核' ? 'success' : 'primary',
                  icon: report.reviewStatus === '已复核' ? 'el-icon-check' : '',
                  completed: report.reviewStatus === '已复核'
                }
              ]
            }));
          } else {
            // 没有数据时保持列表为空
            diagnosisList.value = [];
          }
        } else {
          // 没有患者ID时保持列表为空
          diagnosisList.value = [];
        }
      } catch (error) {
        console.error('加载诊断进度失败:', error);
        // 发生错误时也保持列表为空
        diagnosisList.value = [];
      }
    };
    
    const getStatusType = (status) => {
      const typeMap = {
        completed: 'success',
        reviewed: 'info',
        processing: 'warning',
        pending: 'primary'
      };
      return typeMap[status] || 'info';
    };
    
    const getStatusText = (status) => {
      const textMap = {
        completed: '已完成',
        reviewed: '已复核',
        processing: '处理中',
        pending: '等待中'
      };
      return textMap[status] || '未知';
    };
    
    const getProgressStatus = (progress) => {
      if (progress === 100) return 'success';
      if (progress > 0 && progress < 100) return 'exception';
      return 'primary';
    };
    
    const getStatusColor = (status) => {
      const colorMap = {
        completed: '#67C23A',
        reviewed: '#409EFF',
        processing: '#E6A23C',
        pending: '#409EFF'
      };
      return colorMap[status] || '#909399';
    };
    
    const viewProgressDetail = (diagnosis) => {
      selectedDiagnosis.value = diagnosis;
      detailVisible.value = true;
    };
    
    const handleClose = () => {
      detailVisible.value = false;
      selectedDiagnosis.value = null;
    };
    
    const goToReport = () => {
      // 跳转到报告页面，只有在报告生成后才允许跳转
      if (selectedDiagnosis.value?.status === 'completed') {
        detailVisible.value = false;
        router.push(`/reports/${selectedDiagnosis.value.id}`);
      }
    };
    
    const downloadImage = () => {
      if (selectedDiagnosis.value?.imageUrl) {
        // 创建下载链接
        const link = document.createElement('a');
        link.href = selectedDiagnosis.value.imageUrl;
        link.download = `影像-${selectedDiagnosis.value.id}.jpg`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        console.log('下载影像文件:', selectedDiagnosis.value.id);
      } else {
        alert('影像文件暂不可用');
      }
    };
    
    const shareReport = () => {
      // 生成模拟分享链接
      shareLink.value = `http://localhost:5173/share-report?id=${selectedDiagnosis.value?.id}&token=mock-token-123456`;
      shareVisible.value = true;
    };
    
    const copyLink = () => {
      navigator.clipboard.writeText(shareLink.value).then(() => {
        alert('链接已复制到剪贴板');
      });
    };
    
    const closeShareDialog = () => {
      shareVisible.value = false;
      shareLink.value = '';
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    };
    
    return {
      diagnosisList,
      detailVisible,
      selectedDiagnosis,
      shareVisible,
      shareLink,
      getStatusType,
      getStatusText,
      getProgressStatus,
      getStatusColor,
      viewProgressDetail,
      handleClose,
      goToReport,
      downloadImage,
      shareReport,
      copyLink,
      closeShareDialog,
      formatDate
    };
  }
};
</script>

<style scoped>
.progress-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header h1 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.content {
  flex: 1;
  padding: 30px;
  background-color: #f5f7fa;
  overflow-y: auto;
}

.progress-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-detail {
  padding: 20px 0;
}

.detail-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.detail-header h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  font-weight: 500;
  color: #303133;
  min-width: 80px;
}

.value {
  color: #606266;
}

.process-timeline {
  margin-bottom: 30px;
}

.process-timeline h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.timeline-content h4 {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 16px;
}

.timeline-content p {
  margin: 0;
  color: #606266;
}

.pending-text {
  color: #909399;
  font-size: 14px;
}

.download-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.image-preview {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.image-preview h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.medical-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.medical-image:hover {
  transform: scale(1.02);
}

.download-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.download-section .el-button {
  margin-right: 15px;
}

.share-dialog .el-form-item {
  margin-bottom: 25px;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.qrcode-placeholder {
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  color: #909399;
  margin-bottom: 15px;
}

.qrcode-hint {
  color: #606266;
  margin: 0;
}

@media (max-width: 768px) {
  .content {
    padding: 20px;
  }
  
  .header {
    padding: 0 20px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .qrcode-placeholder {
    width: 150px;
    height: 150px;
  }
}
</style>